from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from login import models

def denglu(request):
    js_t="登陆成功"
    try:
        real_ip=request.META['HTTP_X_FORWARDED_FOR']
        regip = real_ip.split(",")[0]
    except:
        try:
            regip = request.META['REMOTE_ADDR']
        except:
            regip = ""
    ipall=models.allow_ip.objects.filter(ip=regip)
    if ipall:
        if request.method=="POST":
            use=request.POST['username']
            passwd=request.POST['pwd']
            try:
                aaa=models.user.objects.filter(user=use,passwd=passwd)
                if len(aaa)==1:
                    session=request.session
                    session['username']=use
                    if session.get('uri'):
                        url=session['uri']
                        session.pop('uri')
                        return redirect(url)
                    else:
                        print("登陆成功")
                        return redirect("list/")
                else:
                    js_t="登陆失败,用户或密码不正确"
                    return render(request,"login.html",{'js_t':js_t})
            except:
                js_t="登陆失败"
                return render(request,"login.html",{'js_t':js_t})
        else:
            return render(request,"login.html")
    else:
        return HttpResponse("未授权，禁止访问")

def logout(request):
    #实现注销session
    session=request.session
    #session.clear()
    session.pop('username')
    #session.flush()
    return render(request,'login.html')